package com.learning.rpc_common.serializer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (clazz != null && byteBuf.readableBytes() > 4) {
            int len = byteBuf.readableBytes();
            byte[] data = new byte[len];
            byteBuf.getBytes(byteBuf.readerIndex(), data, 0, len);
            System.out.println("decode_data：" + new String(data));
            Object deserialize = serializer.deserialize(clazz, data);
            list.add(deserialize);
        }
    }


}
